import json
import random
# 引入 datetime 模块
import datetime
from django.shortcuts import render,redirect,HttpResponse
from django.http import JsonResponse
from .models import Department,UserInfo,PrettyNum,Admin,Task,Order
from django import forms
# form校验
from django.core.validators import RegexValidator,ValidationError
from django.utils.safestring import mark_safe
from app.utils.pagination import Pagination
from app.utils.bootstrap import BootStrapModelForm,BootStrapForm
from app.utils.encrypt import md5
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
# Create your views here.

def depart_list(request):
    # 部门列表
    queryset = Department.objects.all()
    return render(request, 'depart_list.html', {'queryset':queryset})



def depart_add(request):
    # 添加部门
    if request.method == "GET":
        return render(request,'depart_add.html')

    # 获取用户post 提交过来的数据(title输入为空)
    title = request.POST.get("title")

    # 报错到数据库
    Department.objects.create(title=title)

    # 重定向回部门列表
    return redirect("/app/depart_list/")


def depart_delete(request):
    # 获取id
    nid = request.GET.get('nid')
    # 删除
    Department.objects.filter(id=nid).delete()

    # 重定向回部门列表
    return redirect("/app/depart_list/")


def depart_edit(request,nid):
    # 修改部门
    if request.method == 'GET':
        # 根据nid 获取他的数据[obj,]
        # 返回对象
        row_object = Department.objects.filter(id=nid).first()
        print(row_object.id,row_object.title)
        return render(request,'depart_edit.html',{"row_object":row_object})

    # 获取用户提交的提交
    title = request.POST.get("title")

    # 根据id找到数据库中的数据并进行更新
    Department.objects.filter(id=nid).update(title=title)

    # 重定向回部门列表
    return redirect("/app/depart_list/")


def user_list(request):
    # 用户管理

    # 获取所有用户列表 [obj,obj,obj]
    # queryset = UserInfo.objects.all()
    # for obj in queryset:
    #     print(obj.id,obj.name,obj.account,obj.create_time.strftime("%Y-%m-%d"),obj.get_gender_display(),obj.depart_id)
    #
    # return render(request,"user_list.html",{"queryset":queryset})
    queryset = UserInfo.objects.all()
    page_object = Pagination(request,queryset)
    context = {
        "queryset":page_object.page_queryset,
        "page_string":page_object.html(),
    }
    return render(request,'user_list.html',context)


def user_add(request):
    # 添加用户 (原始方法)
    '''
        原始方式思路 不会采用
        用户提交数据没有校验
        页面上 没一个字段都需要写一次
        关联数据，手动去获取并展示在页面
    '''
    if request.method == "GET":

        context = {
            'gender_choices':UserInfo.gender_choices,
            'depart_list':Department.objects.all()
        }
        return render(request,'user_add.html',context)

    # 获取用户提交的数据
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    account = request.POST.get('ac')
    ctime = request.POST.get('ctime')
    gender_id = request.POST.get('gd')
    depart_id = request.POST.get('dp')

    # 添加数据到数据库
    UserInfo.objects.create(name=user,password=pwd,account=account,create_time=ctime,
                            age=age,
                            gender=gender_id,depart_id=depart_id)

    # 返回到用户列表页面
    return redirect("/app/user/list/")


# 使用from 表单

class UserModelForm(forms.ModelForm):
    class Meta:
        model = UserInfo
        fields = ["name","password","age","account","create_time","gender","depart"]

    # 添加样式
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        # 循环找到所有的插件 添加class=“form-control”
        for name,field in self.fields.items():
            # if name == "password":
            #   continue
            field.widget.attrs = {"class":"form-control","placeholder":field.label}

def user_model_form_add(request):
    # 添加用户 ModelForm
    if request.method == "GET":
        form = UserModelForm()
        return render(request,'user_model_form_add.html',{"form":form})
    # 用户post提交数据 数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        print(form.cleaned_data)
        return redirect("/app/user/list/")
    else:
        print(form.errors)
        return redirect("/app/user/list/")


def user_edit(request,nid):
    # 编辑用户

    # 根据id去数据库获取要编辑的那一行数据
    row_object = UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        form = UserModelForm(instance=row_object)
        return render(request,'user_edit.html',{'form':form})

    form = UserModelForm(data=request.POST,instance=row_object)

    if form.is_valid():
        # 默认保存的是用户输入的所有数据,如果想要用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect("/app/user/list/")
    return render(request,'user_edit.html',{"form":form})


def user_delete(request,nid):
    UserInfo.objects.filter(id=nid).delete()
    return redirect("/app/user/list/")


def pretty_list_1(request):
    # 模拟新增
    # for i in range(300):
    #     PrettyNum.objects.create(mobile="15625775964",price=10,level=1,status=1)
    # 搜索手机号
    '''
     PrettyNum.objects.filter(mobile="156257755964",id=12)
     data_dict = {"mobile":"15625775964","id":123}
     PrettyNum.objects.filter(**data_dict)
    '''
    '''
        查询
        PrettyNum.objects.filter(id=12) 等于12
        PrettyNum.objects.filter(id__=12) 大于12
        PrettyNum.objects.filter(id__gte=12) 大于等于12
        PrettyNum.objects.filter(id__lt=12) 小于12
        PrettyNum.objects.filter(id__lte=12) 小于等于12

        # 模糊查询
        PrettyNum.objects.filter(id__startswidt=12) 筛选出以12开头
        PrettyNum.objects.filter(id__endswith=12)  筛选出以12结尾
        PrettyNum.objects.filter(id__contains=12)  筛选出包含12

    '''

    '''
        分页 
        queryset = PerttyNum.objects.all()
        # 第一页
        queryset = PerttyNum.objects.filter(id=1)[0:10]
        # 第二页
        queryset = PerttyNum.objects.filter(id=1)[10:20]
        # 第三页
        queryset = PerttyNum.objects.filter(id=1)[20:30]
    '''
    # 靓号列表
    # select * from 表 order by level desc;
    data_dict = {}
    search_data = request.GET.get('q',"")

    if search_data:
        data_dict = {"mobile__contains":search_data}
    res = PrettyNum.objects.filter(**data_dict)
    # print(res)

    # 分页
    # 1.根据用户想要访问的页码，计算出起止位置
    page = int(request.GET.get('page',1))
    page_size = 10 # 每页显示10条数据
    start = (page-1)* page_size
    end = page * page_size
    # 数据总条数
    total_count = PrettyNum.objects.filter(**data_dict).order_by("-level").count()
    queryset = PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]

    total_page_count,div = divmod(total_count,page_size)
    if div:
        total_page_count +=1

    # 计算出， 显示当前页的前5页，后5页
    plus = 5
    if total_page_count <= 2*plus+1:
        start_page = 1
        end_page = total_page_count
    else:
        # 数据库中数据比较多 》11页
        # 当前页<5时
        if page <= plus:
            start_page = 1
            end_page = 2*plus+1
        else:
            if(page + plus) > total_page_count:
                start_page = total_page_count - 2 * plus
                end_page = total_page_count
            else:
                start_page = page - plus
                end_page = page + plus
    # 页码
    page_str_list = []
    # 上一页
    if page >1:
        prev = '<li ><a href="?page={}">上一页</a></li>'.format(page-1)
    else:
        prev = '<li ><a href="?page={}">上一页</a></li>'.format(1)
    page_str_list.append(prev)
    for i in range(start_page,end_page+1):
        if i == page:
            ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i,i)
        else:
            ele = '<li><a href="?page={}">{}</a></li>'.format(i,i)
        page_str_list.append(ele)

    # 下一页
    if page < total_page_count:
        prev = '<li ><a href="?page={}">下一页</a></li>'.format(page+1)
    else:
        prev = '<li ><a href="?page={}">下一页</a></li>'.format(total_page_count)

    page_str_list.append(prev)

    # 尾页
    page_str_list.append('<li ><a href="?page={}">尾页</a></li>'.format(total_page_count))

    search_string = """
        <li>
            <form style="float: left;margin-left: -1px" method="get" >
                <input type="text" name="page" style="position: relative;float: left;
                    display: inline-block;width: 88px; border-radius: 0;" class="form-control" placeholder="页码">
                <button style="border-radius: 0" class="btn btn-default" type="submit">跳转</button>
            </form>
        </li>
    """
    page_str_list.append(search_string)
    page_string = mark_safe("".join(page_str_list))

    return render(request,'pretty_list.html',{"queryset":queryset,"search_data":search_data,"page_string":page_string})


def pretty_list(request):
    #  靓号列表
    data_dict = {}
    search_data = request.GET.get('q',"")
    if search_data:
        data_dict["mobile__contains"] = search_data

    queryset = PrettyNum.objects.filter(**data_dict).order_by("-level")

    page_object = Pagination(request,queryset)
    context = {
        "search_data":search_data,
        "queryset":page_object.page_queryset, # 分完页的数据
        "page_string":page_object.html() # 页码
    }
    return  render(request,'pretty_list.html',context)


class PrettyModelForm(forms.ModelForm):
    # 正则表达式校验 手机号码
    # 校验方式一 字段 + 正则
    # mobile = forms.CharField(
    #     label="手机号",
    #     validators=[RegexValidator(r'^1\d{10}$','手机号码格式错误')]
    # )
    class Meta:
        model = PrettyNum
        #fields = "__all__"
        fields = ["mobile",'price','level','status']
        #exclude = ['level']

    def __init__(self, *args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证方式2 钩子方法
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        if len(txt_mobile)!=11:
            # 验证不通过
            raise ValidationError("格式错误")

        # 不允许手机号重复
        # 添加 [正则表达式][手机号不能存在]
        # 数组
        # queryset = PrettyNum.objects.filter(mobile="15625775964")
        # 对象
        # obj = PrettyNum.objects.filter(mobile="15625775964").first()
        # boolea
        # exists = PrettyNum.objects.filter(mobile="15625575964").exists()

        exists = PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过 用户输入的值返回
        return txt_mobile


def pretty_add(request):
    # 添加靓号
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request,'pretty_add.html',{"form":form})

    form = PrettyModelForm(data=request.POST)
    print(form)
    if form.is_valid():
        form.save()
        return redirect('/app/pretty/list/')
    return render(request,'pretty_add.html',{"form":form})


class PrettyEditModelForm(forms.ModelForm):
    class Meta:
        model = PrettyNum
        fields = ['mobile','price','level','status']

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证方式2
    def clean_mobile(self):
        # 当前编辑的哪一行的ID
        # print(self.instance.pk)
        txt_mobile = self.cleaned_data["mobile"]
        exists = PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        print(exists)
        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过，用户输入的值返回
        return txt_mobile



def pretty_edit(request,nid):
    # 编辑靓号
    row_object = PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_object)
        return render(request,'pretty_edit.html',{"form":form})

    form = PrettyEditModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/app/pretty/list/')

    return render(request,'pretty_edit.html',{"form":form})



def pretty_delete(request,nid):
    # 删除靓号
    PrettyNum.objects.filter(id=nid).delete()
    return redirect('/app/pretty/list')


def admin_list(request):
    # 管理员列表

    # 搜索
    data_dict = {}
    search_data = request.GET.get("q","")
    if search_data:
        data_dict["username__contains"] = search_data

    # 根据搜索条件去数据库获取
    queryset = Admin.objects.filter(**data_dict)

    # 分页
    page_object = Pagination(request,queryset)
    context = {
        'queryset':page_object.page_queryset,
        'page_string':page_object.html(),
        "search_data":search_data
    }
    return render(request,'admin_list.html',context)


class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )
    class Meta:
        model = Admin
        fields = ["username","password","confirm_password"]
        widgets = {
            "password":forms.PasswordInput(render_value=True)
        }

    # 构造函数
    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

    def clean_confirm_password(self):
        confirm = md5(self.cleaned_data.get("confirm_password"))
        pwd = self.cleaned_data.get("password")
        if confirm != pwd:
            raise ValidationError("密码不一致")
        return confirm


def admin_add(request):
    # 添加管理员
    title = "新建管理员"
    if request.method == "GET":
        form = AdminModelForm()
        return render(request,'change.html',{'form':form,"title":title})

    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        print(form.cleaned_data)
        # {'username':'admin','password':'123','confirm_password':'333'}
        return redirect('/app/admin/list/')

    return render(request,'change.html',{'form':form,"title":title})

class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = Admin
        fields = ['username']

def admin_edit(request,nid):
    # 编辑管理员
    # 对象/ none
    row_object = Admin.objects.filter(id=nid).first()
    if not row_object:
        return render(request,'error.html',{"msg":"数据存在"})
    title = "编辑管理员"

    if request.method == "GET":
        form = AdminEditModelForm(instance=row_object)
        return render(request,"change.html",{"form":form,"title":title})

    form = AdminEditModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/app/admin/list/')


def admin_delete(request,nid):
    # 删除管理员
    Admin.objects.filter(id=nid).delete()
    return redirect('/app/admin/list/')


class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )
    class Meta:
        model = Admin
        fields = ['password','confirm_password']

        # 构造函数
    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        md5_pwd = md5(pwd)

       # 去数据库校验当前密码和输入面膜是否一致
        exists = Admin.objects.filter(id=self.instance.pk,password=md5_pwd).exists()
        if exists:
            raise ValidationError("不能和之前的密码相同")
        return md5_pwd

    def clean_confirm_password(self):
        confirm = md5(self.cleaned_data.get("confirm_password"))
        pwd = self.cleaned_data.get("password")
        if confirm != pwd:
            raise ValidationError("密码不一致")
        return confirm


def admin_reset(request,nid):
    # 重置密码
    row_object = Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect('/app/admin/list/')

    title = "重置密码 -{}".format(row_object.username)

    if request.method == 'GET':
        form = AdminResetModelForm()
        return render(request,'change.html',{"title":title,"form":form})

    form = AdminResetModelForm(data=request.POST,instance=row_object)
    print(form.is_valid())
    if form.is_valid():
        print("进去了")
        form.save()
        return redirect('/app/admin/list/')

    return render(request, 'change.html', {"title": title})


class LoginForm(BootStrapForm):
    username = forms.CharField(label="用户名",widget=forms.TextInput,required=True)
    password = forms.CharField(label="密码",widget=forms.PasswordInput,required=True)

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)




def login(request):
    # 登录
    if request.method == 'GET':
        form = LoginForm()
        return  render(request,'login.html',{'form':form})

    form = LoginForm(data=request.POST)
    print(form)
    if form.is_valid():
        # 验证成功，获取的用户名和密码
        print(form.cleaned_data)
        # {'username': '15625775964', 'password': '6301b9aef99314ed98a0c206e38476bf'}

        # 去数据库校验用户名和密码是否正确
        admin_object = Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password","用户名或密码错误")
            return render(request,'login.html',{'form':form})

        # 用户名和密码正确
        # 网站生成随机字符串,写到用户浏览器的cookie中，在写入到session中：
        request.session["info"] = {'id' :admin_object.id,"name":admin_object.username}
        return redirect("/app/admin/list/")

        #return HttpResponse("提交成功")

    return render(request,'login.html',{'form':form})


def logout(request):
    # 注销
    request.session.clear()
    return redirect("/app/login/")


class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = Task
        fields = "__all__"
        widgets = {
            "detail":forms.TextInput
            # "detail":forms.Textare
        }


# 任务管理
def task_list(request):
    form = TaskModelForm()
    return render(request,'task_list.html',{"form":form})

@csrf_exempt
def task_ajax(request):
   # < QueryDict: {'n1': ['123'], 'n2': ['456']} >
    print(request.GET.get('n1'))
    print(request.POST)
    data_dict = {"status":True,'data':[11,22,33,44]}
    json_string = json.dumps(data_dict)
    return HttpResponse("成功")
    #return JsonResponse(data_dict)


@csrf_exempt
def task_add(request):
    print(request.POST)
    # 1.用户发送过来的数据进行校验
    form = TaskModelForm(data=request.POST)
    print(form)
    if form.is_valid():
        print("进来了555")
        form.save()
        data_dict = {"status":True}
        return HttpResponse(json.dumps(data_dict))

    data_dict = {"status":False,'error':form.errors}
    return HttpResponse(json.dumps(data_dict,ensure_ascii=False))


class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = Order
        exclude = ["oid","admin"]

def order_list(request):
    queryset = Order.objects.all().order_by('-id')
    page_object = Pagination(request,queryset)
    form = OrderModelForm()
    context = {
        'form':form,
        "queryset":page_object.page_queryset,
        "page_string":page_object.html()
    }
    return render(request,'order_list.html',context)


def order_add(request):
    # 新建订单(ajax请求)
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # 额外增加一些不是用户输入的值
        form.instance.oid = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000,9999))
        # 固定设置管理员id，去哪里获取
        form.instance.admin_id = request.session["info"]['id']
        form.save()
        return JsonResponse({"status":True})

    return  JsonResponse({"status":False,'error':form.errors})


def order_delete(request):
    # 删除
    uid = request.GET.get('uid')
    existe = Order.objects.filter(id=uid).exists()
    if not existe:
        return JsonResponse({"status":False,'error':"数据不存在"})

    Order.objects.filter(id=uid).delete()
    return JsonResponse({"status":True})


def order_detail(request):
    # # 订单详情
    # 方式1
    # uid = request.GET.get("uid")
    # row_object = Order.objects.filter(id=uid).first()
    # if not row_object:
    #     return JsonResponse({"status":False,'error':"数据不存在"})
    #
    # # 从数据库中获取到一个对象 row_object
    # result = {
    #     "status":True,
    #     "data":{
    #         "title":row_object.title,
    #         "price":row_object.price,
    #         "status":row_object.status
    #     }
    # }
    # return JsonResponse({"status":True,'data':result})

    '''
        对象，当前行的所有数据
        row_object = Order.objects.filter(id=uid).first()
        row_object.id
        row_object.title

        字典，{"id":1,"title":"xxx'}
        row_object = Order.objects.filter(id=uid).values("id","title").first()

        queryset = [obj,obj,obj]
        queryset = Order.objects.all()
        queryset = [{"id":1,"title":"xxx"},{"id":2,"title":"xxx'}]
        queryset = Order.objects.all().values("id","title")
    '''

    # 方式2
    uid = request.GET.get("uid")
    row_dict = Order.objects.filter(id=uid).values("title","price","status").first()
    print(row_dict)
    if not row_dict:
        return JsonResponse({"status":False,'error':"数据不存在"})

    # 从数据库中获取也给对象 row_object
    result = {
        "status":True,
        "data":row_dict
    }
    return JsonResponse({"status": True, 'data':result })


@csrf_exempt
def order_edit(request):
    # 编辑订单
    uid = request.GET.get("uid")
    row_object = Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({"status":False,'tip':"数据不存在"})

    form = OrderModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({"status":True})
    return JsonResponse({"status":False,'error':form.errors})


def charts_list(request):
    return render(request,'chart_list.html')


def chart_bar(request):
    # 构造柱状图的数据
    legend = ["销售","销量"]
    series_list = [
        {
            "name": "name1",
            "type": 'bar',
            "data": [15, 20, 36, 10, 10, 10]
        },
        {
            "name": "name2",
            "type": 'bar',
            "data": [19, 29, 16, 25, 35, 10]
        }
    ]
    x_axis = ["1月","2月","3月","4月","5月","6月","7月"]

    result ={
        "status":True,
        "data":{
            'legend':legend,
            'series_list':series_list,
            'x_axis':x_axis
        }

    }

    return JsonResponse(result)







